package server;

import mapper.Mapper;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class RequestProcessorrV extends Thread {
  private Socket socket;
  private String webappsPath;

  private Map<String, Map<String, Map<String, HttpServlet>>> hosts = new HashMap<>();

  public RequestProcessorrV(Socket socket, Map<String, Map<String, Map<String, HttpServlet>>> hosts, String webappsPath) {

    this.socket = socket;
    this.hosts = hosts;
    this.webappsPath = webappsPath;
  }

  @Override
  public void run() {
    try{

      InputStream inputStream = socket.getInputStream();
      // 封装Request对象和Response对象
      Request request = new Request(inputStream);
      Response response = new Response(socket.getOutputStream());

      Map<String, Map<String, HttpServlet>> contexts = hosts.get(request.getHost());//得到虚拟机的项目map

      if(contexts == null) {
        System.out.println("未找到虚拟机");
        response.outputHtml(webappsPath+"404");
        return;
      }
      String url = request.getUrl();
      String webName = url.split("/")[1];
      Map<String, HttpServlet> wrappers = contexts.get(webName);//得到对应项目的wrapper集
      if(wrappers == null) {
        System.out.println("未找到对应项目");
        response.outputHtml(webappsPath+"404");
        return;
      }
      HttpServlet httpServlet = wrappers.get(url.replace("/"+url.split("/")[1],""));


      // 静态资源处理
      if(httpServlet == null) {
        System.out.println("静态资源处理");
        response.outputHtml(webappsPath+request.getUrl());
      }else{
        // 动态资源servlet请求
        System.out.println("动态资源servlet请求");
        httpServlet.service(request,response);
      }
      socket.close();
    }catch (Exception e) {
      e.printStackTrace();
    }

  }

  /**
   *
   * @param path  url，随后要根据url来获取到静态资源的绝对路径，进一步根据绝对路径读取该静态资源文件，最终通过
   *                  输出流输出
   *              /-----> classes
   */
  public void outputHtml(String path, Mapper mapper , OutputStream outputStream) throws IOException {
    // 获取静态资源文件的绝对路径
    String absoluteResourcePath = mapper.getHostList().get(0).getAppBase() + path;

    // 输入静态资源文件
    File file = new File(absoluteResourcePath);
    if(file.exists() && file.isFile()) {
      // 读取静态资源文件，输出静态资源
      StaticResourceUtil.outputStaticResource(new FileInputStream(file),outputStream);
    }else{
      // 输出404
      outputStream.write(HttpProtocolUtil.getHttpHeader404().getBytes());
    }

  }
}
